'use client'

import {useEffect, useRef, useState} from 'react'
import {redirect, useRouter} from "next/navigation";
import {hidden} from "next/dist/lib/picocolors";
import {videoServer} from "@/constants/variables";
import {getUserFromSession} from "@/lib/auth";

export default function UploadForm() {
    // 上传失败提示信息
    const [err, setErr] = useState(null)
    // 上传成功
    const [suc, setSuc] = useState(false)
    // 用户信息
    const [user, setUser] = useState({})
    // 上传的文件
    const [file, setFile] = useState<File>()
    // 上传中
    const [loading, setLoading] = useState(false)

    const router = useRouter()
    const ref = useRef(null)
    const imgref = useRef(null)

    useEffect(() => {
        (async () => {
            const res = await fetch('/api/user', {method: "GET"});
            const resj = await res.json()
            if (!resj.user) {
                router.push('/signin')
            }
            setUser(resj.user)
        })()
    }, [])

    const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        // 阻止表单提交行为
        e.preventDefault()
        if (!file) return

        try {
            // imgref.current.setAttribute('src','/files/avatar.jpg') // can
            // const url = URL.createObjectURL(file);
            // console.log(ref.current)
            // ref.current?.setAttribute('src',url.replace('blob:',''))
            setLoading(true)

            const data = new FormData()
            data.set('file', file)

            const res = await fetch('/api/upload', {
                method: 'POST',
                body: data
            })
            // handle the error
            // if (!res.ok) {
            //     throw new Error(await res.text())
            // }
            const res_json = await res.json()
            setSuc(res_json.success)
            if (!res_json.success) {
                throw new Error(res_json.error)
            }
            setTimeout(() => {
                router.replace('/')
                setLoading(false)
            }, 1500)
        } catch (e: any) {
            // Handle errors here
            setLoading(false)
            setErr(e)
        }
    }

    const upload = () => {
        // 点击图片, 点击图片盖住的input
        ref.current?.click()
    }

    return (
        <main className={'   flex flex-col gap-5 items-center'}>
            {suc && <div
                className={'font-black text-green-600 animate-pulse bg-green-300 p-7 rounded-lg text-center h-20 z-20 w-1/2 absolute -inset-y-0'}>
                上传成功
            </div>}
            <h1 className={'font-bold text-xl'}>Upload Your Video</h1>
            <form className={'flex flex-col items-center gap-5'} onSubmit={onSubmit}>
                <div className={' relative '}>
                    <input
                        ref={ref}
                        type="file"
                        name="file"
                        className={'w-96 h-64 border-2 opacity-0'}
                        onChange={(e) => setFile(e.target.files?.[0])}
                    />
                    <img ref={imgref} onClick={upload} src="/files/upload_to_cload.png" alt=""
                         className={'-inset-y-0 rounded-lg absolute w-96 h-64 '}/>
                </div>
                {/*预览*/}
                {/*<video width="100%" height="720" className="border-none rounded" controls>*/}
                {/*    <source*/}
                {/*        src={''}*/}
                {/*        title="test"*/}
                {/*        type="video/mp4"*/}
                {/*    />*/}
                {/*    你的浏览器不支持该播放器*/}
                {/*</video>*/}
                {Boolean(err) && (
                    <p className='text-red-700'>{err.message}</p>
                )}
                <input
                    className={'disabled:bg-slate-500 hover:bg-green-300 bg-green-200 rounded w-28 py-1'}
                    disabled={loading} type="submit" value="Upload"/>
            </form>
        </main>
    )
}